package com.xgzit.xgzmall.order.interceptor;

import com.xgzit.common.constant.AuthServerConstant;
import com.xgzit.common.vo.MemberEntityVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 用户登录拦截器
 * 1、拦截器必须实现 HandlerInterceptor 这个接口
 * 2、@Component 加入到容器中
 * 3、还需要一个web配置，才能生效 如：OrderWebConfiguration
 * @Author xgz
 * @Date 2021-06-26 19:08
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    /** 为了让其他线程都能共享数据，使用 ThreadLocal **/
    public static ThreadLocal<MemberEntityVo> loginUser = new ThreadLocal<>();

    /** 前置拦截 **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 当前请求的uri
        String requestURI = request.getRequestURI();
        // 这种路径 order/order/status  直接放行
        // 路径匹配器
        boolean match = new AntPathMatcher().match("/order/order/status/**", requestURI);
        boolean payed = new AntPathMatcher().match("/payed/**", requestURI);
        if (match || payed){
            return true;
        }
        // 获取登录用户
        MemberEntityVo attribute = (MemberEntityVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (!Objects.nonNull(attribute)){
            // 没登录就去登录,可以在session放提示
            request.getSession().setAttribute("msg", "请先进行登录！");
            response.sendRedirect("http://auth.xgzmall.com/login.html");
            return false;
        }
        loginUser.set(attribute);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
